package com.lsp.microcommon.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池的配置类
 */
@Configuration
public class ThreadPollConfig {

    //    创建对象并交给容器管理（ioc）
    @Bean
    public ThreadPoolExecutor threadPollExecutor() {
        return new ThreadPoolExecutor(10,
                20,
                600,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                new ThreadFactory() {
//            针对integer的原子类
//            保证高并发情况下数字不会出现重复
                    AtomicInteger v = new AtomicInteger(0);

                    @Override
                    public Thread newThread(Runnable r) {
//                         v.getAndIncrement()获取这个值，并自增
//                        内部加锁处理
                        return new Thread(r, "thread-lsp-" + v.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

}
